package com.eogo.upload.service.impl;

import com.eogo.egexception.EgException;
import com.eogo.egexception.status.EgExceptionStatus;
import com.eogo.upload.service.UploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
public class UploadServiceImpl implements UploadService {

    private static final List<String> ALLOW_TYPES = Arrays.asList("image/jpg","image/png","image/jpeg");

    @Override
    public String uploadImage(MultipartFile file) {
       try {
           //校验文件类型
           String contentType = file.getContentType();
           if(!ALLOW_TYPES.contains(contentType)){
               log.error("无效的文件类型");
               throw new EgException(EgExceptionStatus.INVALID_FILE_TYPE);
           }
           //检验文件内容
           BufferedImage image = ImageIO.read(file.getInputStream());
           if(null == image){
               log.error("无效的文件类型");
               throw new EgException(EgExceptionStatus.INVALID_FILE_TYPE);
           }
           File dest = new File("F:\\mysite\\upload" , file.getOriginalFilename());
           file.transferTo(dest);
           //返回路径
            return "http://image.eogo.com/" + file.getOriginalFilename();
       }catch (Exception e){
           //上传失败
           log.error("上传文件失败");
           throw new EgException(EgExceptionStatus.UPLOAD_FILE_ERROR);
       }

    }
}
